/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using NTasking.Internals;

namespace NTasking
{

    // ReSharper disable InconsistentNaming

    /// <summary>
    /// Implement Ada selective call statements
    /// </summary>
    public class SelectiveCall : SelectiveCallSyntaxEx.SCSyntaxBase
    {

        private static object _currentContextualContinuable;


        /// <summary>
        /// Gets or sets the <see cref="IContinuable"/> last seen while building this instance.
        /// </summary>
        /// <value>The current continuable.</value>
        internal IContinuable CurrentContinuable { get; set; }


        /// <summary>
        /// Sets the <see cref="IContinuable{RetT}"/> last seen while building this instance.
        /// </summary>
        /// <typeparam name="RetT">The type of the result passed to the continuation.</typeparam>
        /// <param name="continuable">The continuable.</param>
        internal void SetContextualContinuable<RetT>(IContinuable<RetT> continuable)
        {
            _currentContextualContinuable = continuable;
        }


        /// <summary>
        /// Gets the <see cref="IContinuable{RetT}"/> last seen while building this instance.
        /// </summary>
        /// <typeparam name="RetT">The type of the result passed to the continuation.</typeparam>
        /// <returns>The continuable</returns>
        internal IContinuable<RetT> GetContextualContinuable<RetT>()
        {
            return _currentContextualContinuable as IContinuable<RetT>;
        }


        /// <summary>
        /// Clear the continubles.
        /// </summary>
        internal void ResetContinubles()
        {
            CurrentContinuable = null;
            _currentContextualContinuable = null;
        }


        private MethodCall _call { get; set; }



        /// <summary>
        /// Gets or sets the timeout alternative.
        /// </summary>
        /// <value>The timeout alternative.</value>
        internal Timeout Timeout { get; set; }


        /// <summary>
        /// Gets or sets the else alternative.
        /// </summary>
        /// <value>The else alternative.</value>
        internal Action Else { get; set; }


        /// <summary>
        /// Gets or sets the abortable part.
        /// </summary>
        /// <value>The abortable part.</value>
        internal Action AbortablePart { get; set; }


        /// <summary>
        /// Execute a new selective call defined by the specified statements.
        /// </summary>
        /// <param name="statements">The statements.</param>
        internal static new void Select(Func<SelectiveCall, SelectiveCallSyntaxEx.ISCComplete> statements)
        {
            if (statements == null)
                throw new ArgumentNullException("statements");

            // Check that this instance can be blocked since select is an Ada
            // 'potentially blocking operation'
            if (!ThreadWrapper.CurrentThread.CanBlock)
                throw Errors.PotentiallyBlockingOperationNotAllowed("select");

            var s = new SelectiveCall();

            statements(s);

            s.Execute();
        }


        /// <summary>
        /// Initializes a new instance of the <see cref="SelectiveCall"/> class.
        /// </summary>
        internal SelectiveCall()
        {
            base.Select = this;
        }


        /// <summary>
        /// Set the call which must be selectively performed.
        /// </summary>
        /// <param name="selectiveCall">The call.</param>
        /// <returns></returns>
        internal SelectiveCallSyntaxEx.SelectiveActionCall CreateActionCall(MethodCall selectiveCall)
        {
            _call = selectiveCall;

            CurrentContinuable = selectiveCall;

            return new SelectiveCallSyntaxEx.SelectiveActionCall { Select = this };
        }


        /// <summary>
        /// Set the call which must be selectively performed.
        /// </summary>
        /// <param name="selectiveCall">The call.</param>
        /// <returns></returns>
        internal SelectiveCallSyntaxEx.SelectiveFuncCall<RetT> CreateFuncCall<RetT>(MethodCall selectiveCall)
        {
            _call = selectiveCall;

            SetContextualContinuable((IContinuable<RetT>)selectiveCall);

            return new SelectiveCallSyntaxEx.SelectiveFuncCall<RetT> { Select = this };
        }


        /// <summary>
        /// Executes this instance.
        /// </summary>
        private void Execute()
        {
            if (Else != null)
            {
                SynchronizedObject.ConditionalEntryCall(_call);

                if (_call.Context.ResultIsSet)
                    _call.Continue();
                else
                    Else();
            }
            else if (AbortablePart != null)
            {
                if (!ThreadWrapper.CurrentThread.Abortable)
                    throw Errors.AsynchronousSelectNotAllowed();

                SynchronizedObject.AsynchronousSelect(_call, AbortablePart);

                if (_call.Context.ResultIsSet)
                    _call.Continue();
            }
            else
            {
                Timeout.Freeze();

                SynchronizedObject.TimedEntryCall(_call, Timeout.Value);

                if (_call.Context.ResultIsSet)
                    _call.Continue();
                else
                    Timeout.Continue();
            }
        }

    }

}
